"use client";
import { useState, useEffect } from "react"
import { Card, Badge, Pagination, Button } from "flowbite-react";
export default function Expercise() {
    const [envVar, setEnvVar] = useState({ API_BASE_URL: "http://localhost:7775" });
    const [currentPage, setCurrentPage] = useState(1);
    const [bodyPart, setBodyPart] = useState("");
    const [equipment, setEquipment] = useState("");
    const onPageChange = (page) => setCurrentPage(page);
    const [refresh,setRefresh] = useState(false);
    const pageSize = 9;

    const [exercise, setExercise] = useState([{
        bodyPart: "",
        equipment: "",
        gifUrl: "",
        id: "",
        name: "",
        target: "",
        secondaryMuscles: [],
        instructions: []
    }])
    const fetchItems = async () => {


        const response = await fetch(envVar['API_BASE_URL'] + '/exercises/list?limit=' + pageSize
            + "&bodyPart=" + bodyPart
            + "&equipment=" + equipment
            + '&offset=' + (currentPage - 1) * pageSize); 
        if (!response.ok) {
            throw new Error('Failed to fetch data');
        }
        return response.json();
    };

    useEffect(() => {
        fetch('/api/env')
            .then(response => response.json())
            .then(data => {
                console.log(data);
                setEnvVar(data)
            })
            .catch(error => console.error('Error fetching environment variable:', error));
    }, []);


    useEffect(() => {
        if (envVar != null) {
            const loadExpercise = async () => {
                try {
                    const data = await fetchItems();
                    setExercise(data)
                } catch (error) {
                    console.error('Error loading items:', error);
                }
            };

            loadExpercise();
        }

    }, [envVar, currentPage,refresh]);

    const bodyPartZh = {
        "back": "背部",
        "cardio": "有氧运动",
        "chest": "胸",
        "lower arms": "下臂",
        "lower legs": "小腿",
        "neck": "脖子",
        "shoulders": "肩膀",
        "upper arms": "上臂",
        "upper legs": "大腿",
        "waist": "腰",

    };

    const equipmentZh = {


        "assisted": "辅助",
        "band": "带",
        "barbell": "杠铃",
        "body weight": "自重",
        "bosu ball": "博苏球",
        "cable": "电缆",
        "dumbbell": "哑铃",
        "elliptical machine": "椭圆机",
        "ez barbell": "轻松的杠铃",
        "hammer": "锤",
        "kettlebell": "壶铃",
        "leverage machine": "杠杆机",
        "medicine ball": "药球",
        "olympic barbell": "奥林匹克杠铃",
        "resistance band": "阻力带",
        "roller": "滚筒",
        "rope": "绳",
        "skierg machine": "Skierg machine",
        "sled machine": "雪橇机",
        "smith machine": "smith machine",
        "stability ball": "stability ball",
        "stationary bike": "固定自行车",
        "stepmill machine": "阶梯机",
        "tire": "tire",
        "trap bar": "trap bar",
        "upper body ergometer": "上半身测力计",
        "weighted": "weighted",
        "wheel roller": "wheel roller"
    };

    function handleBodyPartClick(item){
        setBodyPart(item);
        setEquipment("");
        setCurrentPage(1);
        setRefresh(!refresh);
    }

    
    function handleEquimentClick(item){
        setEquipment(item);
        setBodyPart("");
        setCurrentPage(1);
        setRefresh(!refresh);
    }

    return <>
        <div className="flex w-full  gap-10 p-10">
            <div className="flex flex-col w-1/4 gap-5">
                <h5 className="text-xl font-bold text-gray-900 dark:text-white">
                    锻炼部位
                </h5>
                <div className="flex  gap-2 flex-wrap">
                    {
                        Object.keys(bodyPartZh).map((item, index) => (
                            <Badge color="info" key={index} onClick={()=>handleBodyPartClick(item)}>{bodyPartZh[item]}</Badge>
                        ))
                    }
                </div>

                <h5 className="text-xl font-bold text-gray-900 dark:text-white">
                    使用设备
                </h5>
                <div className="flex  gap-2 flex-wrap">
                    {
                        Object.keys(equipmentZh).map((item, index) => (
                            <Badge color="info" key={index} onClick={()=>handleEquimentClick(item)}>{equipmentZh[item]}</Badge>
                        ))
                    }
                </div>

                <h5 className="text-xl font-bold text-gray-900 dark:text-white">
                    当前过滤
                </h5>

                <div className="flex  gap-2 flex-wrap">
                    {bodyPart!="" && <Badge color="info" onClick={()=>handleBodyPartClick(item)}>{bodyPartZh[bodyPart]}</Badge>  }
                    {equipment!="" && <Badge color="info" onClick={()=>handleEquimentClick(item)}>{equipmentZh[equipment]}</Badge>}
                   
                </div>
                <Button onClick={()=>handleBodyPartClick("")}>刷新页面</Button>

            </div>

            <div className="flex flex-col">
                <div className="flex flex-wrap w-full justify-around  gap-10">
                    {
                        exercise.map((item, index) => (
                            <Card className="max-w-sm" imgSrc={envVar['API_BASE_URL'] + item.gifUrl.split("7775")[1]} horizontal key={index}>
                                <h5 className="text-2xl font-bold tracking-tight text-gray-900 dark:text-white">
                                    {item.name}
                                </h5>
                                <div className="flex flex-wrap gap-2">
                                    <Badge color="info">{bodyPartZh[item.bodyPart] ? bodyPartZh[item.bodyPart] : item.bodyPart}</Badge>
                                    <Badge color="purple">{equipmentZh[item.equipment] ? equipmentZh[item.equipment] : item.equipment}</Badge>
                                </div>
                                <div className="flex flex-wrap gap-2">
                                    {item.secondaryMuscles.map((secondaryMuscle, secondaryMuscleIndex) => (
                                        <Badge color="gray" key={secondaryMuscleIndex}>{secondaryMuscle}</Badge>
                                    ))}
                                </div>
                                {
                                    item.instructions.map((instruction, instructionIndex) => (
                                        <section className="font-normal text-gray-700 dark:text-gray-400" key={instructionIndex}>
                                            {instruction}
                                        </section>
                                    ))
                                }

                            </Card>
                        )

                        )
                    }

                </div>
                <div className="flex overflow-x-auto sm:justify-center">
                    <Pagination currentPage={currentPage} totalPages={100} onPageChange={onPageChange} />
                </div>
            </div>
        </div>

    </>
}